//
//  ClubSquareMemberViewController.swift
//  77Club
//
//  Created by Apple on 2024/12/27.
//

import UIKit
import JXSegmentedView

class ClubSquareMemberViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    private var segmentedDataSource = JXSegmentedTitleDataSource()
    private var listContainerView: JXSegmentedListContainerView!
    
    private var memberList = [ClubForumMemberModel]()
    private var banMemberList = [ClubForumMemberModel]()
    private var managerMemberList = [ClubForumMemberModel]()
    
    private var memberListVC = ClubMemberListViewController()
    private var banListVC = ClubBanListViewController()
    private var managerListVC = ClubManagerListViewController()
    
    var updateSquareMember:(()->())?
    
    var selIndex = 0 {
        didSet{
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.segmentedView.selectItemAt(index: self.selIndex)
            }
        }
    }
    //是否是管理员
    var isAdmin = false
    //是否有禁言的权限
    var isMute = true
    var isShowManager = false
    var isShowBan = false
    var master_user: ClubForumMemberModel? {
        didSet{
            memberListVC.master_user = master_user
        }
    }
    var banNum = 0
    var adminNum = 0
    var memberNum = 0
    
    var communityId = "" {
        didSet{
            loadData()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            segmentedView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        segmentedView.leading(56).top(CGFloat.statusHeight).height(44).width(CGFloat.screenWidth - 56.0)
        
        segmentedDataSource = JXSegmentedTitleDataSource()
        segmentedDataSource.titles = ["论坛成员","禁言","管理员"]
        
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = "#969799".toColor
        segmentedDataSource.titleSelectedColor = "#323233".toColor
        segmentedDataSource.titleNormalFont = 14.font_semiBold!
        segmentedDataSource.titleSelectedFont = 14.font_semiBold!
        segmentedDataSource.itemSpacing = 11.0.Scale
        segmentedDataSource.isItemSpacingAverageEnabled = false
        segmentedView.dataSource = segmentedDataSource
        
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorColor = "#323233".toColor
        indicator.indicatorHeight = 2.0.Scale
//        indicator.indicatorWidth = 55.0.Scale
//        indicator.indicatorCornerRadius = 2.0.Scale
        indicator.verticalOffset = 5.0.Scale
        segmentedView.indicators = [indicator]
        
        segmentedView.delegate = self
        segmentedView.backgroundColor = .clear
        
        listContainerView = JXSegmentedListContainerView(dataSource: self)
        view.addSubview(listContainerView)
        
        segmentedView.listContainer = listContainerView
        
        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateMemberList), name: .updateForumMemberState, object: nil)
    }
    
    @objc private func updateMemberList(){
        self.updateTitlesData()
        updateSquareMember?()
    }
    
    private func loadData(){
        
        
        ToastUtil.show()
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "ForumMember")
        
        netGroup.enter()
        workingQueue.async {
            Task{
                let res = await self.network.request(.squareMemberList(gid: self.communityId, role: "", keyword: "", page: 1), type: ClubForumMemberModel.self)
                if let models = res.models, res.isSuccess {
                    self.memberList = models
                    netGroup.leave()
                }
            }
        }
        netGroup.enter()
        workingQueue.async {
            Task{
                let res = await self.network.request(.squareMemberList(gid: self.communityId, role: "1", keyword: "", page: 1), type: ClubForumMemberModel.self)
                if let models = res.models, res.isSuccess {
                    self.managerMemberList = models
                    netGroup.leave()
                }
            }
        }
        netGroup.enter()
        workingQueue.async {
            Task{
                let res = await self.network.request(.squareBanMember(gid: self.communityId, page: 1), type: ClubForumMemberModel.self)
                if let models = res.models, res.isSuccess {
                    self.banMemberList = models
                    netGroup.leave()
                }
            }
        }
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                ToastUtil.dismiss()
                var memberStr = "论坛成员"
                if self.memberNum > 0 {
                    let memNum = ClubGlobalTool.shared.formatNumber(num: "\(self.memberNum)")
                    memberStr = "论坛成员(\(memNum)人)"
                }
                var banStr = "禁言"
                if self.banNum > 0 {
                    let bNum = ClubGlobalTool.shared.formatNumber(num: "\(self.banNum)")
                    banStr = "禁言(\(bNum)人)"
                }
                var managerStr = "管理员"
                if self.adminNum > 0 {
                    let aNum = ClubGlobalTool.shared.formatNumber(num: "\(self.adminNum)")
                    managerStr = "管理员(\(aNum)人)"
                }
                
                self.memberListVC.dataSource = self.memberList
                self.memberListVC.isAdmin = self.isAdmin
                self.memberListVC.isMute = self.isMute
                self.memberListVC.communityId = self.communityId
                self.banListVC.dataSource = self.banMemberList
                self.banListVC.isAdmin = self.isAdmin
                self.managerListVC.dataSource = self.managerMemberList
                self.banListVC.communityId = self.communityId
                self.managerListVC.communityId = self.communityId
                self.segmentedDataSource.titles.removeAll()
                self.segmentedDataSource.titles.append(memberStr)
                if self.isShowBan {
                    self.segmentedDataSource.titles.append(banStr)
                }
                if self.isShowManager {
                    self.segmentedDataSource.titles.append(managerStr)
                }
                self.segmentedView.reloadData()
            }
            
        }
    }
    
    private func updateTitlesData(){
        Task {
            let res = await network.request(.communityTop(communityID: communityId),type: ClubGameCommunityModel.self)
            if res.isSuccess, let model = res.model {
                self.banNum = model.ban_num
                self.adminNum = model.admin_num
                self.memberNum = model.guanzhu_num
                
                var memberStr = "论坛成员"
                if self.memberNum > 0 {
                    let memNum = ClubGlobalTool.shared.formatNumber(num: "\(self.memberNum)")
                    memberStr = "论坛成员(\(memNum)人)"
                }
                var banStr = "禁言"
                if self.banNum > 0 {
                    let bNum = ClubGlobalTool.shared.formatNumber(num: "\(self.banNum)")
                    banStr = "禁言(\(bNum)人)"
                }
                var managerStr = "管理员"
                if self.adminNum > 0 {
                    let aNum = ClubGlobalTool.shared.formatNumber(num: "\(self.adminNum)")
                    managerStr = "管理员(\(aNum)人)"
                }
                
                self.segmentedDataSource.titles.removeAll()
                self.segmentedDataSource.titles.append(memberStr)
                if self.isShowBan {
                    self.segmentedDataSource.titles.append(banStr)
                }
                if self.isShowManager {
                    self.segmentedDataSource.titles.append(managerStr)
                }
                self.segmentedView.reloadData()
            }
        }
    }
}

//MARK: JXSegmentedListContainerViewDataSource ClubMemberListViewController
extension ClubSquareMemberViewController:JXSegmentedListContainerViewDataSource, JXSegmentedViewDelegate {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedDataSource.dataSource.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        
        if index == 0 {
            return memberListVC
        }else if index == 1 {
            return banListVC
        }
        return managerListVC
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
    }
}
